package com.ibm.cognos.imt.service;

import com.ibm.cognos.imt.config.BiServerConfig;
import com.ibm.cognos.imt.model.ReportHtml;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by eric on 7/12/2014.
 */

@Service
public class ReportHtmlFactory {
    Document document;

    @Autowired
    BiServerConfig biServerConfig;


    public ReportHtml parse(final String html) {
        document = Jsoup.parse(html);
        ReportHtml reportHtml = new ReportHtml();
        reportHtml.setBody(getBodyContent());
//        reportHtml.setJsFunctions(getJsFunctions());
        return reportHtml;
    }

    private String getBodyContent() {
        Element body = document.select("body").first();
        //remove script tags
        Elements jsCodeSnippets = body.select("script");
        for (Element element : jsCodeSnippets) {
            element.remove();
        }
        return externalizeOriginalLink(body.html());
    }

//    private String[] getJsFunctions(){
//        Elements jsFunctions = document.select("script") ;
//        Iterator<Element> it =jsFunctions.iterator();
//        while (it.hasNext()) {
//            Element element = (Element)(it.next());
//            System.out.println(element.html());
//        }
//        return new String[]{};
//    }

    private String externalizeOriginalLink(final String html){
        String result = html.replace("../", biServerConfig.gatewayResourceURI());
        result = result.replace("..\\", biServerConfig.gatewayResourceURI());
        result = result.replace("src=\"?", "src=\"" + biServerConfig.gatewayCgi() + "?");
        return result;
    }

    public List<ReportHtml> parseOutputPages(String[] pages) {
        List<ReportHtml> result = new ArrayList<ReportHtml>();
        for (String page : pages) {
            result.add(parse(page));
        }
        return result;
    }

}
